﻿using Mrc.Data;
using System;
using System.Collections.Generic;
using System.Text;
using Mrc.Entity;
using Chloe;
using System.Linq.Expressions;
using System.Linq;

namespace Mrc.Application
{
    public interface ISysOrgService : IServiceBase<SysOrg>, IMrcService
    {
        List<SysOrg> GetParentOrgs(string orgType);
        List<SysOrg> GetList(Expression<Func<SysOrg, bool>> where);
        List<SysOrgPermission> GetPermissions(string orgId);
        void SetPermission(string orgId, List<string> permissionList);
        void Delete(string orgId, string operatorId);

    }
    public class SysOrgService : ServiceBase<SysOrg>, ISysOrgService
    {
        public SysOrgService(IDbContext dbContext, IServiceProvider services) : base(dbContext, services)
        {

        }
        public List<SysOrg> GetParentOrgs(string orgType)
        {
            var orgTypeQuery = this.DbContext.Query<SysOrgType>().Where(a => a.Id == orgType);
            var q = this.DbContext.Query<SysOrg>().Where(a => Sql.Equals(a.Type, orgTypeQuery.First().ParentId));
            List<SysOrg> ret = q.ToList();
            return ret;
        }
        public List<SysOrg> GetList(Expression<Func<SysOrg, bool>> where)
        {
            return this.DbContext.Query<SysOrg>().FilterDeleted().Where(where).ToList();
        }
        public List<SysOrgPermission> GetPermissions(string orgId)
        {
            return this.DbContext.Query<SysOrgPermission>().Where(t => t.OrgId == orgId).ToList();
        }
        public void SetPermission(string orgId, List<string> permissionList)
        {
            List<SysOrgPermission> roleAuths = permissionList.Select(a => new SysOrgPermission()
            {
                Id = Guid.NewGuid().ToString(),
                OrgId = orgId,
                PermissionId = a
            }).ToList();

            this.DbContext.DoWithTransaction(() =>
            {
                this.DbContext.Delete<SysOrgPermission>(a => a.OrgId == orgId);
                this.DbContext.InsertRange(roleAuths);
            });
        }
        public void Delete(string id, string operatorId)
        {
            this.DbContext.SoftDelete<SysOrg>(id, operatorId);
        }
    }
}
